package com.igeek.boot.config;

import com.igeek.boot.entity.Pet;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.format.FormatterRegistry;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.util.UrlPathHelper;

/**
 * @package com.igeek.boot.config
 * @Description  实现mvc配置
 * @Author LittlePunk [296526219@qq.ccom]
 * @Version 2022.1
 * @Date 2023/12/6 15:47
 *
 *  * 基于MVC定制Web开发
 *  * 实现方式：@Configuration + implements WebMvcConfigurer + 重写方法
 *  *
 *  * 全面接管Web开发
 *  * 实现方式：@EnableWebMvc + extends DelegatingWebMvcConfiguration
 */
@Configuration
//@EnableWebMvc
public class WebConfig {
    //替换底层组件
    @Bean
    public WebMvcConfigurer webMvcConfigurer() {
        return new WebMvcConfigurer() {
            //配置路径匹配
            @Override
            public void configurePathMatch(PathMatchConfigurer configurer) {
                UrlPathHelper urlPathHelper = new UrlPathHelper();
                //默认按照全路径处理请求URL Servlet mapping such as "/myServlet/*"
                //urlPathHelper.setAlwaysUseFullPath(true);
                //默认true时会去除请求URL中的分号;   设置为false，则不去除分号
                urlPathHelper.setRemoveSemicolonContent(false);
                configurer.setUrlPathHelper(urlPathHelper);
            }

            //添加转换器
            @Override
            public void addFormatters(FormatterRegistry registry) {
                //String -> Pet
                Converter<String, Pet> converter = new Converter<String, Pet>() {
                    @Override
                    public Pet convert(String source) {  //source 龙猫#3
                        if (StringUtils.hasLength(source)) {
                            String[] splits = source.split("#");
                            Pet pet = new Pet(splits[0], Integer.valueOf(splits[1]));
                            return pet;
                        }
                        return null;
                    }
                };

                registry.addConverter(converter);
            }


            //添加拦截器
            /*@Override
            public void addInterceptors(InterceptorRegistry registry) {

            }*/
        };
    }
}
